"""
推送服务路由
处理设备注册、监控控制相关的API
"""
import logging
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import Optional
from monitoring_service import monitoring_service
from push_service import send_test_notification, is_fcm_enabled

logger = logging.getLogger(__name__)

router = APIRouter()


# ========== 数据模型 ==========

class DeviceRegisterRequest(BaseModel):
    """设备注册请求"""
    token: str


class MonitoringStatusResponse(BaseModel):
    """监控状态响应"""
    isActive: bool
    intervalSeconds: int
    monitoringStockCount: int
    lastUpdateTime: int
    registeredDevices: int
    startTime: Optional[str] = None
    fcmEnabled: bool


# ========== API 端点 ==========

@router.post("/device/register")
async def register_device(request: DeviceRegisterRequest):
    """
    注册设备Token
    App启动时将FCM Token注册到后端
    """
    try:
        logger.info(f"📱 注册设备Token: {request.token[:20]}...")
        
        success = monitoring_service.register_device(request.token)
        
        # 发送测试通知
        if success:
            await send_test_notification(request.token)
        
        return {
            "success": True,
            "message": "设备已注册",
            "registered_devices": len(monitoring_service.registered_devices)
        }
        
    except Exception as e:
        logger.error(f"❌ 注册设备失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/device/unregister")
async def unregister_device(request: DeviceRegisterRequest):
    """
    取消注册设备Token
    """
    try:
        logger.info(f"📱 取消注册设备Token: {request.token[:20]}...")
        
        success = monitoring_service.unregister_device(request.token)
        
        return {
            "success": success,
            "message": "设备已取消注册" if success else "设备不存在",
            "registered_devices": len(monitoring_service.registered_devices)
        }
        
    except Exception as e:
        logger.error(f"❌ 取消注册设备失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/monitoring/start")
async def start_monitoring(interval: int = 30):
    """
    启动后端监控服务
    后端会持续监控股票，发现买卖点时推送给所有注册的设备
    
    Args:
        interval: 监控间隔（秒），默认30秒，最小5秒
    """
    try:
        if interval < 5:
            raise HTTPException(status_code=400, detail="监控间隔不能小于5秒")
        
        if interval > 3600:
            raise HTTPException(status_code=400, detail="监控间隔不能大于1小时")
        
        logger.info(f"🚀 请求启动监控服务，间隔：{interval}秒")
        
        success = await monitoring_service.start(interval)
        
        if not success:
            raise HTTPException(status_code=409, detail="监控服务已在运行中")
        
        return {
            "success": True,
            "message": "监控服务已启动",
            "interval": interval,
            "registered_devices": len(monitoring_service.registered_devices)
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"❌ 启动监控失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/monitoring/stop")
async def stop_monitoring():
    """
    停止后端监控服务
    """
    try:
        logger.info(f"⏹️ 请求停止监控服务")
        
        success = await monitoring_service.stop()
        
        if not success:
            raise HTTPException(status_code=409, detail="监控服务未运行")
        
        return {
            "success": True,
            "message": "监控服务已停止"
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"❌ 停止监控失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/monitoring/status", response_model=MonitoringStatusResponse)
async def get_monitoring_status():
    """
    查询监控状态
    """
    try:
        status = monitoring_service.get_status()
        status['fcmEnabled'] = is_fcm_enabled()
        
        logger.debug(f"📊 查询监控状态: {status['isActive']}")
        
        return status
        
    except Exception as e:
        logger.error(f"❌ 查询监控状态失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/devices/count")
async def get_devices_count():
    """
    查询已注册设备数量
    """
    try:
        count = len(monitoring_service.registered_devices)
        
        return {
            "count": count,
            "devices": [
                f"{token[:10]}...{token[-10:]}" 
                for token in monitoring_service.registered_devices
            ] if count <= 10 else []
        }
        
    except Exception as e:
        logger.error(f"❌ 查询设备数量失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))

